﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PortalCurriculo.Domain;
using PortalCurriculo.MvcWebUI.Helpers;
using PortalCurriculo.MvcWebUI.Models;

namespace PortalCurriculo.MvcWebUI.Controllers
{
    public class CurriculoController : ControllerBase<CurriculoModel, Curriculo>
    {
        public ActionResult MasterEdicao(int? idProfissional)
        {
            return PartialView(SelecionarCurriculos(idProfissional));
        }

        private static IEnumerable<CurriculoModel> SelecionarCurriculos(int? idProfissional)
        {
            var curriculos = idProfissional == null || LoggedHelper.IsSameProfessional()
                                   ? ContextSession<Profissional>(SessionName.ProfissionalLogado).Curriculoes.ToList()
                                   : new Curriculo { IdProfissional = idProfissional.Value }.SelecionarPorProfissional();

            return new CurriculoModel().CriarViewModel(curriculos);
        }

        [UserAuthorize(UserType = UserAuthorizeAttribute.UserTypes.Profissional)]
        public override ActionResult Manter(int? id)
        {
            base.Manter(id);
            return PartialView();
        }

        [UserAuthorize(UserType = UserAuthorizeAttribute.UserTypes.Profissional)]
        public override ActionResult Manter(CurriculoModel model)
        {
            if (model.IdProfissional == 0)
            {
                var profissional = WebSession<Profissional>(SessionName.ProfissionalLogado);
                if (profissional != null)
                    model.IdProfissional = profissional.Id;

                model.DataCadastro = DateTime.Now;
            }

            if (model.Id == 0 && new Curriculo().Existe(model.IdProfissional, model.Objetivo))
                throw new DuplicateNameException();

            model.DataUltimaAtualizacao = DateTime.Now;
            base.Manter(model);

            return PartialView("Listar", SelecionarCurriculos(model.IdProfissional));
        }

        [UserAuthorize(UserType = UserAuthorizeAttribute.UserTypes.Profissional)]
        public ActionResult Excluir(int id)
        {
            new Curriculo().Inative<Curriculo>(id);
            var profissional = WebSession<Profissional>(SessionName.ProfissionalLogado);

            return PartialView("Listar", SelecionarCurriculos(profissional.Id));
        }

        public void PreencherViewBag(int? idNivelProfissional = null)
        {
            var niveis = new NivelProfissional().SelectAllActive<NivelProfissional>().OrderBy(m => m.Descricao);
            ViewBag.IdNivelProfissional = niveis.ToSelectList(x => x.Descricao, x => x.Id.ToString(), idNivelProfissional.ToString());
        }
    }
}
